package cn.xuchunh;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class FirstServlet
 */
@WebServlet("/FirstServlet")
public class FirstServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public FirstServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("Get a post Request");
		System.out.println("Headers:");
		Enumeration<String> names = request.getHeaderNames();
		while (names.hasMoreElements()) {
			String name = names.nextElement();
			System.out.println("\t" + name + ":" + request.getHeader(name));
		}
		System.out.println("Request Body: ");
		Map<String, String[]> params = request.getParameterMap();
		Iterator<String> iterator = params.keySet().iterator();
		while (iterator.hasNext()) {
			String printContent;
			String key = iterator.next();
			printContent = key + ":";
			String[] values = params.get(key);
			if (values != null) {
				for (String value : values) {
					printContent += value + "|";
				}
			}
			System.out.println(printContent);
		}
		PrintWriter writer = response.getWriter();
		writer.append("success");
		writer.flush();
		writer.close();
	}

}
